package com.ipet.cart.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ipet.cart.mapper.CartMapper;
import com.ipet.cart.pojo.Cart;


@Service
public class CartServiceImpl implements CartService {

	@Autowired
	private CartMapper cartMapper;

	@Override
	public List<Cart> findCartByUserId(Long userId) {
//		Cart cart = new Cart();
//		cart.setUserId(userId);
//		//通过通用Mapper查询购物车信息
		return cartMapper.findCartByUserId(userId);
	}

	@Override
	public void updateCartNum(Cart cart) {
		//添加修改时间
		cart.setUpdated(new Date());
		cartMapper.updateNum(cart);
	}

	@Override
	public void deleteCart(Long userId, Long itemId) {
		Cart cart = new Cart();
		cart.setUserId(userId);
		cart.setItemId(itemId);
		cartMapper.deleteCart(cart);
		//调用父类的方法  规范:调用父类的方法时最好添加super
//		super.deleteByWhere(cart);
		
		
	}
	
	/**
	 * 1.如果用户第一次添加该商品则进行入库操作
	 * 2.如果用户已经添加商品，则应该修改商品数量 int num = 原来数量+新增数量
	 */
	@Override
	public void saveCart(Cart cart) {
		//根据itemId和userId判断用户是否买过该商品
		Cart cartTemp = new Cart();
		cartTemp.setItemId(cart.getItemId());
		cartTemp.setUserId(cart.getUserId());
//		Cart cartDB = super.queryByWhere(cartTemp);
		Cart cartDB = cartMapper.findCartByUserIdAndItemId(cartTemp);
		if(cartDB!=null){
			cartDB.setNum(cart.getNum()+cartDB.getNum());
			cartDB.setUpdated(new Date());
			cartMapper.updateByPrimaryKeySelective(cartDB);
		}else{
			cart.setCreated(new Date());
			cart.setUpdated(cart.getCreated());
			cartMapper.insert(cart);
		}
	}


}
